package com.test.controller;

import com.test.entity.ImgInfo;
import com.test.service.ImgInfoService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author welcome
 */
@RestController
@CrossOrigin
@RequestMapping("download")
public class DownloadController {
    @Resource
    ImgInfoService service;

    private static final String BASE_PATH = "E:\\tomcat\\apache-tomcat-9.0.39\\webapps\\upload\\";

    @PostMapping("img")
    public void download(Integer id, HttpServletResponse response) {
        ImgInfo imgInfo = service.selectById(id);

        try {
            if(imgInfo!=null){
                String url = ResourceUtils.getURL(BASE_PATH).getPath()+"";
                String decode = URLDecoder.decode(url,"utf-8");
                String str1=imgInfo.getImgAddress();
                String str2 = str1.substring(str1.lastIndexOf("/")+1);
                FileInputStream inputStream=new FileInputStream(decode+str2);
                response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(str2,"utf-8"));
                ServletOutputStream outputStream = response.getOutputStream();
                IOUtils.copy(inputStream,outputStream);
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);
            }else {
                System.out.println("文件未找到");
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

}
